import urllib
import xml.dom.minidom
import os
import time 
import zipfile
import re
import interestrates_pb2
import xml.etree.ElementTree as ET
from protobuf.socketrpc import RpcService
import protobuf.socketrpc.channel
import socket
import sys

import logging
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)

localtime = time.localtime()
datetoday = time.strftime("%Y%m%d", localtime)
print datetoday
datetoday = '20140131'
xmlstr = ''
localIRXMLZipFileName = "InterestRates_" + datetoday + ".zip"
urlIRXMLFile = "http://www.marketerra.com/news/" + localIRXMLZipFileName
pxyies = {}
urlopener = urllib.URLopener(pxyies)
urlopener.open(urlIRXMLFile)
if os.path.isfile(localIRXMLZipFileName):
    os.remove(localIRXMLZipFileName)
if os.path.isfile(localIRXMLZipFileName):            
    print localIRXMLZipFileName + " already exist"
else:
    print "Saving file " + localIRXMLZipFileName
    
    urlopener.retrieve(urlIRXMLFile, localIRXMLZipFileName)
    zfile = zipfile.ZipFile(localIRXMLZipFileName)
    for name in zfile.namelist():
        (dirname, filenameunzipped) = os.path.split(name)
        unzipFileName = filenameunzipped + ''
        if unzipFileName != 'Disclaimer.txt':
            print "Unzipping " + filenameunzipped + " from " + localIRXMLZipFileName
            fd = open(filenameunzipped, "w")
            fd.write(zfile.read(name))
            fd.close()                
            fd = open(filenameunzipped, "r")
            xmlstr = fd.read()
            fd.close()
            print xmlstr
rc = []
def getText(nodelist, elemName=''):
    elem = elemName
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
        else:
            if node.localName == 'tenor' or node.localName == 'parrate':
                getText(node.childNodes, node.localName)
    return elem.join(rc)

curvepoint = "curvepoint"
dom = xml.dom.minidom.parseString(xmlstr)
curvePoints = dom.getElementsByTagName(curvepoint)
for curvePointValue in curvePoints:
    curvePoint = getText(curvePointValue.childNodes, ':')
    rc = []
    print "Last curve point %s " % curvePoint
    cp = re.split(":", curvePoint)
    print cp[0]
    print cp[1]

tree = ET.parse(filenameunzipped)
root = tree.getroot()
irCurve = interestrates_pb2.interestRateCurve()
assert not irCurve.HasField("effectiveasof")
irCurve.effectiveasof = root.find("./effectiveasof").text
assert not irCurve.HasField("currency")
irCurve.currency = root.find("./currency").text
assert not irCurve.HasField("baddayconvention")
irCurve.baddayconvention = root.find("./baddayconvention").text
elem = root.find("deposits")
for node in elem:
        irCurve.deposit.daycountconvention = elem.find("./daycountconvention").text
        irCurve.deposit.snaptime = elem.find("./snaptime").text
        irCurve.deposit.spotdate = elem.find("./spotdate").text
        irCurve.deposit.calendars.calendar = elem.find("./calendars/calendar").text
elem = root.findall("deposits/curvepoint/tenor")
for node in elem:
        irCurve.deposit.curvepoint.add().tenor = node.text
elem = root.findall("deposits/curvepoint/maturitydate")
cnt = 0;
for node in elem:
        irCurve.deposit.curvepoint[cnt].maturitydate = node.text
        cnt = cnt + 1
elem = root.findall("deposits/curvepoint/parrate")
cnt = 0;
for node in elem:
        irCurve.deposit.curvepoint[cnt].parrate = float(node.text)
        cnt = cnt + 1

elem = root.find("swaps")
for node in elem:
        irCurve.swap.fixeddaycountconvention = elem.find("./fixeddaycountconvention").text
        irCurve.swap.floatingdaycountconvention = elem.find("./floatingdaycountconvention").text
        irCurve.swap.fixedpaymentfrequency = elem.find("./fixedpaymentfrequency").text
        irCurve.swap.floatingpaymentfrequency = elem.find("./floatingpaymentfrequency").text
        irCurve.swap.snaptime = elem.find("./snaptime").text
        irCurve.swap.spotdate = elem.find("./spotdate").text
        irCurve.swap.calendars.calendar = elem.find("./calendars/calendar").text
elem = root.findall("swaps/curvepoint/tenor")
for node in elem:
        irCurve.swap.curvepoint.add().tenor = node.text
elem = root.findall("swaps/curvepoint/maturitydate")
cnt = 0;
for node in elem:
        irCurve.swap.curvepoint[cnt].maturitydate = node.text
        cnt = cnt + 1
elem = root.findall("swaps/curvepoint/parrate")
cnt = 0;
for node in elem:
        irCurve.swap.curvepoint[cnt].parrate = float(node.text)
        cnt = cnt + 1

print irCurve.ByteSize(), irCurve
f = open('irCurve.txt', 'w')
f.write(irCurve.SerializeToString())
hostname = '192.168.1.113'
port = 8090

s = None
for res in socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM):
    af, socktype, proto, canonname, sa = res
    try:
	s = socket.socket(af, socktype, proto)
    except socket.error, msg:
	print 'can not create socket', msg
	s = None
	continue
    try:
	s.connect(sa)
	print 'connected socket', s, sa
    except socket.error, msg:
	print 'can not connect socket', msg
	s.close()
	s = None
    	print 'got socket',  af, socktype, proto, canonname, sa
	continue
    break
if s is None:
    print 'could not open socket'
    sys.exit(1)
while True:   
    s.send(str(irCurve.ByteSize()))
    s.send(irCurve.SerializeToString())
    data = s.recv(1024)
    print 'Received', repr(data)
    time.sleep(120)

#class Callback:
#	def run(self, response):
#		print "Received Response :%s" % response

#channel = protobuf.socketrpc.channel.SocketRpcChannel(hostname, port)
#controller = channel.newController()

#service = interestrates_pb2.PushService_Stub(channel)
#service.Push(controller, irCurve, Callback())

#if controller.failed():
#	print "Rpc failed %s : %s" %s (controller.error, controller.reason)

###############################
#class Callback(irCurve, Status):
#        log.info("Asynchronous response: "+response__str__())

#try:
#        log.info("Making asynchronous call")
#        Status = service.Push(irCurve, callback=callback)
#except  Exception, ex:
#        log.exception(ex)

def int_to_rgb(n):
    b = (n & 0xff0000) >> 16
    g = (n & 0x00ff00) >> 8
    r = (n & 0x0000ff)
    return (r, g, b)
